# 1.读取一张图像文件并显示它。
# 2.用户使用鼠标从图像中选择一个感兴趣区域（ROI）。
# 3.显示用户选择的ROI区域。
# 4.统计ROI像素点颜色个数，并对颜色做出判断【这里只对黄色 蓝色 绿色 白色做出判断即可】
# 5. print输出颜色


import cv2
import numpy as np

img = cv2.imread('../images/roi_color.png')

x, y, w, h = cv2.selectROI('image', img, False)
roi_img = img[y:y + h, x:x + w]
cv2.imshow('ROI', roi_img)
cv2.waitKey(0)

# 统计ROI像素点颜色个数，并对颜色做出判断【这里只对黄色 蓝色 绿色 白色做出判断即可】
# 将ROI区域转换成HSV颜色空间
hsv_img = cv2.cvtColor(roi_img, cv2.COLOR_BGR2HSV)
blue_count = yellow_count = green_count = white_count = 0
for i in range(0, h):
    for j in range(0, w):
        H, S, V = hsv_img[i, j]
        if 100 <= H <= 124:
            blue_count += 1
        elif 11 <= H <= 34:
            yellow_count += 1
        elif 35 <= H <= 77:
            green_count += 1
        elif 0 <= H <= 180:
            white_count += 1
print(f"ROI区域颜色统计结果：\n"
      f"蓝色：{blue_count}\n"
      f"黄色：{yellow_count}\n"
      f"绿色：{green_count}\n"
      f"白色：{white_count}\n")

# 正常来说是要把颜色写到图片中，但是opencv严格不支持中文
# cv2.putText()

color = "None"
if yellow_count * 2 >= h * w:
    color = "yellow"
elif blue_count * 2 >= h * w:
    color = "blue"
elif green_count * 2 >= h * w:
    color = "green"
elif white_count * 2 >= h * w:
    color = "white"
print(color)

# 或者建立字典映射
color_dict = {
    "yellow": yellow_count,
    "blue": blue_count,
    "green": green_count,
    "white": white_count
}
color = max(color_dict, key=color_dict.get)
print(color)